//
//  Login_Controller.m
//  MIT-AffordSuperMarket
//
//  Created by apple on 15/11/9.
//  Copyright © 2015年 河南大实惠电子商务有限公司. All rights reserved.
//

#import "Login_Controller.h"
//vendor
#import "TPKeyboardAvoidingScrollView.h"
//untils
#import "UIColor+Hex.h"
#import "UITextField+Space.h"
#import "Global.h"
#import "ManagerGlobeUntil.h"
#import "VerificationPhoneNumber.h"
#import "ManagerHttpBase.h"
#import "NSString+Conversion.h"
//controllers
#import "RegisterOneStepViewController.h"
//model
#import "UserInfoModel.h"
#import "MTA.h"
@interface Login_Controller ()
@property(nonatomic, strong)UITextField *userNameTextfield;//用户名
@property(nonatomic, strong)UITextField *userPasswordTextfield;//用户密码
@property(nonatomic, strong)UIButton *autoLoginBtn;//自动登录按钮
@property(nonatomic, strong)UIButton *loginBtn;//登录按钮
@property(nonatomic, strong)UIButton *forgetPasswordBtn;//忘记密码按钮
@property(nonatomic, strong)TPKeyboardAvoidingScrollView *rootScrollView;
@end

@implementation Login_Controller

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#efeeee"];
    [self addRightNavItemWithTitle:@"注册"];
    [self setNavgationTitleViewWithImageName:@"Nav_logo"];
    [self addBackNavItem];
    [self setupSubView];
}
-(void)viewWillAppear:(BOOL)animated
{
     [super viewWillAppear:animated];
    if (self.userName.length != 0) {
        self.userNameTextfield.text = self.userName;
    }
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    //实时监听账号输入
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldIsChanging) name:UITextFieldTextDidChangeNotification object:nil];
    [MTA trackPageViewBegin:@"注册"];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
    self.userName = @"";
    [MTA trackPageViewEnd:@"注册"];
}

#pragma mark -- 登录条件判断
//点击获取验证码之前的判断
- (BOOL)requestLoginParamsIsRight
{
        if (![VerificationPhoneNumber isMobileNumber:self.userNameTextfield.text])
        {
            NSString * errorMsg = @"手机号码格式不正确，请重新输入";
            [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:errorMsg inView:self.view];
            //[self.userNameTextfield becomeFirstResponder];
            return NO;
            
        }
        else if (self.userPasswordTextfield.text.length == 0)
    {
        NSString * errorMsg = @"密码不能为空";
        [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:errorMsg inView:self.view];
        //[self.userPasswordTextfield becomeFirstResponder];
       
        return NO;
        
    }
    return YES;
}
#pragma mark -- request data
//用户登录协议
- (void)loadLoginData {
   
    [[ManagerGlobeUntil sharedManager]showHUDWithMsg:@"加载中..."
                                              inView:self.view];
        //请求参数说明： SIGNATURE  设备识别码
        ManagerHttpBase *manager = [ManagerHttpBase sharedManager];
        NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
        [parameter setObject:self.userNameTextfield.text forKey:@"PHONE"];
        [parameter setObject:self.userPasswordTextfield.text forKey:@"PASSWORD"];
        __weak typeof(self)weakSelf = self;
        [manager parameters:parameter customPOST:@"user/login" success:^(AFHTTPRequestOperation *operation, id responseObject) {
            [[ManagerGlobeUntil sharedManager] hideHUDFromeView:self.view];
            if([responseObject isKindOfClass:[NSDictionary class]]){
                if ([responseObject isKindOfClass:[NSDictionary class]]) {
                    NSDictionary *dataDic = (NSDictionary*)responseObject;
                    NSString *msg = [dataDic objectForKey:@"MSG"];
                    NSString *state = [NSString stringTransformObject:[dataDic objectForKey:@"STATE"]];//状态码
                    if ([state isEqualToString:@"0"]) {//请求成功
                        if (dataDic.count != 0) {
                            UserInfoModel *model = [[UserInfoModel alloc]init];
                            model.token = [NSString stringTransformObject:[[dataDic objectForKey:@"OBJECT"] objectForKey:@"TOKEN"]];
                            model.nickName = [NSString stringTransformObject:[[[dataDic objectForKey:@"OBJECT"] objectForKey:@"USER"] objectForKey:@"NICKNAME"]];
                            model.userImage = [NSString stringTransformObject:[[[dataDic objectForKey:@"OBJECT"] objectForKey:@"USER"] objectForKey:@"AVATOR"]];
                            model.userLevel = [NSString stringTransformObject:[[[dataDic objectForKey:@"OBJECT"] objectForKey:@"USER"] objectForKey:@"LEVEL"]];
                            model.userMoney = [NSString stringTransformObject:[[[dataDic objectForKey:@"OBJECT"] objectForKey:@"USER"] objectForKey:@"MONEY"]];
                            model.userInvitecode = [NSString stringTransformObject:[[[dataDic objectForKey:@"OBJECT"] objectForKey:@"USER"] objectForKey:@"INVITECODE"]];
                            model.userInviteuserID = [NSString stringTransformObject:[[[dataDic objectForKey:@"OBJECT"] objectForKey:@"USER"] objectForKey:@"INVITEUSERID"]];
                            model.userName = weakSelf.userNameTextfield.text;
                            model.userPassword = weakSelf.userPasswordTextfield.text;
                            [[ManagerGlobeUntil sharedManager] updataUserInfoWithModel:model];
                        }
                        [weakSelf loginSuccess];
                    }else {//请求失败
                        [[ManagerGlobeUntil sharedManager]showTextHUDWithMsg:msg inView:weakSelf.view];
                    }
                    
                }
            }
        } failure:^(bool isFailure) {
            [[ManagerGlobeUntil sharedManager] hideHUDFromeView:weakSelf.view];

        }];
    
}

- (void)loginSuccess {
    [ManagerGlobeUntil sharedManager].transactionLogin = YES;
    if (self.supperControllerType == kShoppingCartGoToJieSuanPushToLogin_ControllerSupperController || self.supperControllerType == kProductDetetailPushToLogin_ControllerSupperController || self.supperControllerType == kUserCenterPushToLogin_ControllerSupperController || self.supperControllerType == kServiceDetailPushtoLogin_ControllerSupperController) {
        [self dismissViewControllerAnimated:YES completion:nil];
    } else {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
}
#pragma mark -- 监听账号输入框值的变化
- (void)textFieldIsChanging {
    NSLog(@"textFieldText = %@",self.userNameTextfield.text);
}
#pragma mark -- TPKeyboardAvoidingScrollViewDelegate
- (void)touchScrollView {
    
}
#pragma mark -- button Action
////自动登录事件
//- (void)autoLoginEvent:(id)sender {
//    UIButton *butotn = (UIButton*)sender;
//    butotn.selected = !butotn.selected;
//}
//登录事件
- (void)loginEvent:(id)sender {
   //隐藏键盘
    [self hideKeyboard];
     if ([self requestLoginParamsIsRight]) {
         
         [self loadLoginData];
     }
}
//忘记密码事件
- (void)forgetPasswordEvent:(id)sender {
    RegisterOneStepViewController *registerOneStepVC = [[RegisterOneStepViewController alloc]init];
    registerOneStepVC.typeOfView = OneStepIsFindTheSecret;
    [self.navigationController pushViewController:registerOneStepVC animated:YES];
}
//注册
- (void)rigthBtnAction:(id)sender {
    RegisterOneStepViewController *registerOneStepVC = [[RegisterOneStepViewController alloc]init];
    registerOneStepVC.typeOfView = OneStepIsRegister;
    [self.navigationController pushViewController:registerOneStepVC animated:YES];
}

- (void)backBtnAction:(id)sender {
    if (self.supperControllerType == kShoppingCartGoToJieSuanPushToLogin_ControllerSupperController || self.supperControllerType == kProductDetetailPushToLogin_ControllerSupperController || self.supperControllerType == kUserCenterPushToLogin_ControllerSupperController || self.supperControllerType == kServiceDetailPushtoLogin_ControllerSupperController) {
        [self dismissViewControllerAnimated:YES completion:nil];
    } else {
         [self.navigationController popToRootViewControllerAnimated:YES];
    }
   
    
}
#pragma mark -- 初始化子视图
- (void)setupSubView {
    UIImage *textfieldBackgroundImage = [UIImage imageNamed:@"intPutBg"];
    textfieldBackgroundImage = [textfieldBackgroundImage stretchableImageWithLeftCapWidth:6 topCapHeight:6];
    
    //根视图容器
    _rootScrollView = [[TPKeyboardAvoidingScrollView alloc]initWithFrame:CGRectMake(0
                                                                                    , 0
                                                                                    , CGRectGetWidth(self.view.bounds)
                                                                                    , CGRectGetHeight(self.view.bounds))];
    _rootScrollView.scrollViewDelegate = (id<TPKeyboardAvoidingScrollViewDelegate>)self;
    _rootScrollView.showsHorizontalScrollIndicator = NO;
    _rootScrollView.showsVerticalScrollIndicator = NO;
    _rootScrollView.backgroundColor = [UIColor clearColor];
    _rootScrollView.contentSize = CGSizeMake(CGRectGetWidth(self.view.bounds)
                                             , CGRectGetHeight(self.view.bounds) - 64);
    [self.view addSubview:_rootScrollView];
    //用户名
    _userNameTextfield = [[UITextField alloc]initWithFrame:CGRectMake(10
                                                                      , 22
                                                                      , CGRectGetWidth(self.view.bounds) - 2*10
                                                                      , 44)];
    [_userNameTextfield setDirection:kLeftEdge edgeSpace:8];
    _userNameTextfield.placeholder = @"手机号";
    _userNameTextfield.font = [UIFont systemFontOfSize:16];
    _userNameTextfield.text = self.userName;
    _userNameTextfield.background = textfieldBackgroundImage;
    [_rootScrollView addSubview:_userNameTextfield];
    //用户密码
    _userPasswordTextfield = [[UITextField alloc]initWithFrame:CGRectMake(CGRectGetMinX(_userNameTextfield.frame)
                                                                          , CGRectGetMaxY(_userNameTextfield.frame) + 22
                                                                          , CGRectGetWidth(_userNameTextfield.bounds)
                                                                          , CGRectGetHeight(_userNameTextfield.bounds))];
    [_userPasswordTextfield setDirection:kLeftEdge edgeSpace:8];
    _userPasswordTextfield.placeholder = @"密码";
    _userPasswordTextfield.font = [UIFont systemFontOfSize:16];
    _userPasswordTextfield.secureTextEntry = YES;
    _userPasswordTextfield.background = textfieldBackgroundImage;
    [_rootScrollView addSubview:_userPasswordTextfield];
    
//    //自动登录
//    _autoLoginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [_autoLoginBtn setImage:[UIImage imageNamed:@"fxk"] forState:UIControlStateNormal];
//    _autoLoginBtn.backgroundColor = [UIColor clearColor];
//    _autoLoginBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
//    [_autoLoginBtn setImage:[UIImage imageNamed:@"fxk_choose"] forState:UIControlStateSelected];
//    _autoLoginBtn.frame = CGRectMake(CGRectGetMinX(_userPasswordTextfield.frame)
//                                     , CGRectGetMaxY(_userPasswordTextfield.frame) + 5
//                                     , 100
//                                     , 44);
//    [_autoLoginBtn setTitle:@"自动登录" forState:UIControlStateNormal];
//    _autoLoginBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 8, 0, 0);
//    _autoLoginBtn.titleLabel.font = [UIFont systemFontOfSize:15];
//    _autoLoginBtn.selected = YES;
//    [_autoLoginBtn addTarget:self action:@selector(autoLoginEvent:) forControlEvents:UIControlEventTouchUpInside];
//    [_autoLoginBtn setTitleColor:[UIColor colorWithHexString:@"#72706f"] forState:UIControlStateNormal];
//    [_rootScrollView addSubview:_autoLoginBtn];
    
    //登录按钮
    _loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _loginBtn.frame = CGRectMake(CGRectGetMinX(_userPasswordTextfield.frame)
                                 , CGRectGetMaxY(_userPasswordTextfield.frame) + 40
                                 , CGRectGetWidth(_userPasswordTextfield.bounds)
                                 , CGRectGetHeight(_userPasswordTextfield.bounds));
    [_loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    UIImage *loginImage = [UIImage imageNamed:@"login_Btn"];
    loginImage = [loginImage stretchableImageWithLeftCapWidth:6 topCapHeight:6];
    [_loginBtn setBackgroundImage:loginImage forState:UIControlStateNormal];
    [_loginBtn addTarget:self action:@selector(loginEvent:) forControlEvents:UIControlEventTouchUpInside];
    [_rootScrollView addSubview:_loginBtn];
    
    //忘记密码
    _forgetPasswordBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _forgetPasswordBtn.frame = CGRectMake(CGRectGetWidth(self.view.bounds) - 140
                                          , CGRectGetMaxY(_loginBtn.frame) + 4
                                          , 125, 44);
    [_forgetPasswordBtn setTitle:@"忘记密码?" forState:UIControlStateNormal];
    _forgetPasswordBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [_forgetPasswordBtn setTitleColor:[UIColor colorWithHexString:@"#72706f"] forState:UIControlStateNormal];
    _forgetPasswordBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    _forgetPasswordBtn.backgroundColor = [UIColor clearColor];
    [_forgetPasswordBtn addTarget:self action:@selector(forgetPasswordEvent:) forControlEvents:UIControlEventTouchUpInside];
    [_rootScrollView addSubview:_forgetPasswordBtn];
    
}
#pragma mark -- 隐藏键盘
//隐藏键盘
- (void)hideKeyboard {
    
        [self.userNameTextfield resignFirstResponder];
        [self.userPasswordTextfield resignFirstResponder];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
